package com.aterrizar.dominio.Neo4J;


import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;


public class ManagerNeo {

    private static ThreadLocal<GraphDatabaseService> tlGrafo= new ThreadLocal<GraphDatabaseService>();

    public static <T> T runInSessionInDatabase(NeoOperation<T> operation, String database) {
        if (tlGrafo.get() == null) {
            tlGrafo.set(crearBaseDeDatos(database));
        }
        T result;
        Transaction tx = null;
        try {
            tx = tlGrafo.get().beginTx();
            result = operation.execute();
            tx.success();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (tx != null) {
                tx.close();
            }
        }
        return result;
    }

    public static GraphDatabaseService crearBaseDeDatos(String database) {
        
    	final GraphDatabaseService grafo = new GraphDatabaseFactory().newEmbeddedDatabase(database);
        
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
            	grafo.shutdown();
            }
        }));

        return grafo;
    }

    public static <T> T runInSession(NeoOperation<T> operation) {
        return runInSessionInDatabase(operation, "neo4jDatabase");
    }

    public static GraphDatabaseService getSession() {
        return tlGrafo.get();
    }
}